package com.my.demo.resource.cusstom;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by LeiXuMeng on 2017/7/17.
 */
@Component("customTokenExtractor")
public class CustomTokenExtractor extends BearerTokenExtractor{
    private static final Log logger = LogFactory.getLog(CustomTokenExtractor.class);
    @Override
    protected String extractToken(HttpServletRequest request) {
        String token = this.extractHeaderToken(request);
        if(token == null) {
            logger.debug("Token not found in headers. Trying request parameters.");
            token = request.getParameter("access_token");
            if(token == null){
                token = request.getParameter("oauth_token");
                if(token == null) {
                    logger.debug("Token not found in request parameters.  Not an OAuth2 request.");
                } else {
                    request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, "Bearer");
                }
            }
        }

        return token;
    }
}
